<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/myblogs/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/myblogs/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/myblogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/myblogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/myblogs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/myblogs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/myblogs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/myblogs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/myblogs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="排序,算法," />





  <link rel="alternate" href="/myblogs/atom.xml" title="天行健の博客" type="application/atom+xml" />






<meta name="description" content="绪论身为程序员，十大排序是是所有合格程序员所必备和掌握的，并且热门的算法比如快排、归并排序还可能问的比较细致，对算法性能和复杂度的掌握有要求。bigsai作为一个负责任的Java和数据结构与算法方向的小博主，在这方    面肯定不能让读者们有所漏洞。跟着本篇走，带你捋一捋常见的十大排序算法，轻轻松松掌握！ 首先对于排序来说大多数人对排序的概念停留在冒泡排序或者JDK中的Arrays.sort()，">
<meta property="og:type" content="article">
<meta property="og:title" content="程序员必知必会的十大算法">
<meta property="og:url" content="https://joy_24.gitee.io/2020/11/26/sort-algorithm/index.html">
<meta property="og:site_name" content="天行健の博客">
<meta property="og:description" content="绪论身为程序员，十大排序是是所有合格程序员所必备和掌握的，并且热门的算法比如快排、归并排序还可能问的比较细致，对算法性能和复杂度的掌握有要求。bigsai作为一个负责任的Java和数据结构与算法方向的小博主，在这方    面肯定不能让读者们有所漏洞。跟着本篇走，带你捋一捋常见的十大排序算法，轻轻松松掌握！ 首先对于排序来说大多数人对排序的概念停留在冒泡排序或者JDK中的Arrays.sort()，">
<meta property="og:locale">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/1.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/2.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/3.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/4.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/5.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/6.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/7.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/8.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/9.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/10.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/11.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/12.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/13.png">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/14.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/15.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/16.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/17.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/18.jpg">
<meta property="article:published_time" content="2020-11-26T06:43:49.000Z">
<meta property="article:modified_time" content="2021-10-26T02:12:44.006Z">
<meta property="article:author" content="Joy Wang">
<meta property="article:tag" content="排序,算法">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://joy_24.gitee.io/2020/11/26/sort-algorithm/"/>





  <title>程序员必知必会的十大算法 | 天行健の博客</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a target="_blank" rel="noopener" href="https://github.com/JoyWJ" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>


    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/myblogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">天行健の博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个开发博客的初学者。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/myblogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/myblogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/myblogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/myblogs/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/myblogs/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/myblogs/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/11/26/sort-algorithm/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">程序员必知必会的十大算法</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-26T14:43:49+08:00">
                2020-11-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index">
                    <span itemprop="name">算法</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  23
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="绪论"><a href="#绪论" class="headerlink" title="绪论"></a>绪论</h2><p>身为程序员，十大排序是是所有合格程序员所必备和掌握的，并且热门的算法比如快排、归并排序还可能问的比较细致，对算法性能和复杂度的掌握有要求。bigsai作为一个负责任的Java和数据结构与算法方向的小博主，在这方    面肯定不能让读者们有所漏洞。跟着本篇走，带你捋一捋常见的十大排序算法，轻轻松松掌握！</p>
<p>首先对于排序来说大多数人对排序的概念停留在冒泡排序或者JDK中的Arrays.sort()，手写各种排序对很多人来说都是一种奢望，更别说十大排序算法了，不过还好你遇到了本篇文章！</p>
<p>对于排序的分类，主要不同的维度比如复杂度来分、内外部、比较非比较等维度来分类。我们正常讲的十大排序算法是内部排序，我们更多将他们分为两大类：基于<strong>「比较和非比较」</strong>这个维度去分排序种类。</p>
<ul>
<li><strong>「非比较类的有桶排序、基数排序、计数排序」</strong>。也有很多人将排序归纳为8大排序，那就是因为基数排序、计数排序是建立在桶排序之上或者是一种特殊的桶排序，但是基数排序和计数排序有它特有的特征，所以在这里就将他们归纳为10种经典排序算法。而比较类排序也可分为</li>
<li>比较类排序也有更细致的分法，有基于交换的、基于插入的、基于选择的、基于归并的，更细致的可以看下面的脑图。</li>
</ul>
<p><img src="/myblogs/2020/11/26/sort-algorithm/1.png" alt="脑图"></p>
<h2 id="交换类"><a href="#交换类" class="headerlink" title="交换类"></a>交换类</h2><h3 id="冒泡排序"><a href="#冒泡排序" class="headerlink" title="冒泡排序"></a>冒泡排序</h3><p>冒泡排序，又称起泡排序，它是一种基于交换的排序典型，也是快排思想的基础，冒泡排序是一种稳定排序算法，时间复杂度为O(n^2).基本思想是：<strong>「循环遍历多次每次从前往后把大元素往后调，每次确定一个最大(最小)元素，多次后达到排序序列。」</strong>(或者从后向前把小元素往前调)。</p>
<p>具体思想为(把大元素往后调)：</p>
<ul>
<li>从第一个元素开始往后遍历，每到一个位置判断是否比后面的元素大，如果比后面元素大，那么就交换两者大小，然后继续向后，这样的话进行一轮之后就可以保证<strong>「最大的那个数被交换交换到最末的位置可以确定」</strong>。</li>
<li>第二次同样从开始起向后判断着前进，如果当前位置比后面一个位置更大的那么就和他后面的那个数交换。但是有点注意的是，这次并不需要判断到最后，只需要判断到倒数第二个位置就行(因为第一次我们已经确定最大的在倒数第一，这次的目的是确定倒数第二)</li>
<li>同理，后面的遍历长度每次减一，直到第一个元素使得整个元素有序。</li>
</ul>
<p>例如<code>2 5 3 1 4</code>排序过程如下：</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/2.png"></p>
<p>实现代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public void  maopaosort(int[] a) &#123;</span><br><span class="line">  &#x2F;&#x2F; TODO Auto-generated method stub</span><br><span class="line">  for(int i&#x3D;a.length-1;i&gt;&#x3D;0;i--)</span><br><span class="line">  &#123;</span><br><span class="line">    for(int j&#x3D;0;j&lt;i;j++)</span><br><span class="line">    &#123;</span><br><span class="line">      if(a[j]&gt;a[j+1])</span><br><span class="line">      &#123;</span><br><span class="line">        int team&#x3D;a[j];</span><br><span class="line">        a[j]&#x3D;a[j+1];</span><br><span class="line">        a[j+1]&#x3D;team;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="快速排序"><a href="#快速排序" class="headerlink" title="快速排序"></a>快速排序</h3><p>快速排序是对冒泡排序的一种改进，采用递归分治的方法进行求解。而快排相比冒泡是一种不稳定排序,时间复杂度最坏是O(n^2),平均时间复杂度为O(nlogn),最好情况的时间复杂度为O(nlogn)。</p>
<p>对于快排来说，<strong>「基本思想」</strong>是这样的</p>
<ul>
<li>快排需要将序列变成两个部分，就是<strong>「序列左边全部小于一个数」</strong>，<strong>「序列右面全部大于一个数」</strong>，然后利用递归的思想再将左序列当成一个完整的序列再进行排序，同样把序列的右侧也当成一个完整的序列进行排序。</li>
<li>其中这个数在这个序列中是可以随机取的，可以取最左边，可以取最右边，当然也可以取随机数。但是<strong>「通常」</strong>不优化情况我们取最左边的那个数。</li>
</ul>
<p><img src="/myblogs/2020/11/26/sort-algorithm/3.png"></p>
<p>实现代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">public void quicksort(int [] a,int left,int right)</span><br><span class="line">&#123;</span><br><span class="line">  int low&#x3D;left;</span><br><span class="line">  int high&#x3D;right;</span><br><span class="line">  &#x2F;&#x2F;下面两句的顺序一定不能混，否则会产生数组越界！！！very important！！！</span><br><span class="line">  if(low&gt;high)&#x2F;&#x2F;作为判断是否截止条件</span><br><span class="line">    return;</span><br><span class="line">  int k&#x3D;a[low];&#x2F;&#x2F;额外空间k，取最左侧的一个作为衡量，最后要求左侧都比它小，右侧都比它大。</span><br><span class="line">  while(low&lt;high)&#x2F;&#x2F;这一轮要求把左侧小于a[low],右侧大于a[low]。</span><br><span class="line">  &#123;</span><br><span class="line">    while(low&lt;high&amp;&amp;a[high]&gt;&#x3D;k)&#x2F;&#x2F;右侧找到第一个小于k的停止</span><br><span class="line">    &#123;</span><br><span class="line">      high--;</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;&#x2F;这样就找到第一个比它小的了</span><br><span class="line">    a[low]&#x3D;a[high];&#x2F;&#x2F;放到low位置</span><br><span class="line">    while(low&lt;high&amp;&amp;a[low]&lt;&#x3D;k)&#x2F;&#x2F;在low往右找到第一个大于k的，放到右侧a[high]位置</span><br><span class="line">    &#123;</span><br><span class="line">      low++;</span><br><span class="line">    &#125;</span><br><span class="line">    a[high]&#x3D;a[low];   </span><br><span class="line">  &#125;</span><br><span class="line">  a[low]&#x3D;k;&#x2F;&#x2F;赋值然后左右递归分治求之</span><br><span class="line">  quicksort(a, left, low-1);</span><br><span class="line">  quicksort(a, low+1, right);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="插入类排序"><a href="#插入类排序" class="headerlink" title="插入类排序"></a>插入类排序</h2><h3 id="直接插入排序"><a href="#直接插入排序" class="headerlink" title="直接插入排序"></a>直接插入排序</h3><p>直接插入排序在所有排序算法中的是最简单排序方式之一。和我们上学时候 从前往后、按高矮顺序排序，那么一堆高低无序的人群中，从第一个开始，如果前面有比自己高的，就直接插入到合适的位置。<strong>「一直到队伍的最后一个完成插入」</strong>整个队列才能满足有序。</p>
<p>直接插入排序遍历比较时间复杂度是每次O(n),交换的时间复杂度每次也是O(n),那么n次总共的时间复杂度就是O(n^2)。有人会问折半(二分)插入能否优化成O(nlogn),答案是不能的。因为二分只能减少查找复杂度每次为O(logn),而插入的时间复杂度每次为O(n)级别，这样总的时间复杂度级别还是O(n^2).</p>
<p>插入排序的具体步骤：</p>
<ul>
<li>选取当前位置(当前位置前面已经有序) 目标就是将当前位置数据插入到前面合适位置。</li>
<li>向前枚举或者二分查找，找到待插入的位置。</li>
<li>移动数组，赋值交换，达到插入效果。</li>
</ul>
<p><img src="/myblogs/2020/11/26/sort-algorithm/4.png"><br>实现代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public void insertsort (int a[])</span><br><span class="line">&#123;</span><br><span class="line">  int team&#x3D;0;</span><br><span class="line">  for(int i&#x3D;1;i&lt;a.length;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    System.out.println(Arrays.toString(a));</span><br><span class="line">    team&#x3D;a[i];</span><br><span class="line">    for(int j&#x3D;i-1;j&gt;&#x3D;0;j--)</span><br><span class="line">    &#123;</span><br><span class="line"></span><br><span class="line">      if(a[j]&gt;team)</span><br><span class="line">      &#123;</span><br><span class="line">        a[j+1]&#x3D;a[j];</span><br><span class="line">        a[j]&#x3D;team; </span><br><span class="line">      &#125; </span><br><span class="line">      else &#123;</span><br><span class="line">        break;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="希尔排序"><a href="#希尔排序" class="headerlink" title="希尔排序"></a>希尔排序</h3><p>直接插入排序因为是O(n^2),在数据量很大或者数据移动位次太多会导致效率太低。很多排序都会想办法拆分序列，然后组合，希尔排序就是以一种特殊的方式进行预处理，考虑到了<strong>「数据量和有序性」</strong>两个方面纬度来设计算法。使得序列前后之间小的尽量在前面，大的尽量在后面，进行若干次的分组别计算，最后一组即是一趟完整的直接插入排序。</p>
<p>对于一个<code>长串</code>，希尔首先将序列分割(非线性分割)而是<strong>「按照某个数模」</strong>(<code>取余</code>这个类似报数1、2、3、4。1、2、3、4)这样形式上在一组的分割先<strong>「各组分别进行直接插入排序」</strong>,这样<strong>「很小的数在后面」</strong>可以通过<strong>「较少的次数移动到相对靠前」</strong>的位置。然后慢慢合并变长，再稍稍移动。</p>
<p>因为每次这样插入都会使得序列变得更加有序，稍微有序序列执行直接插入排序成本并不高。所以这样能够在合并到最终的时候基本小的在前，大的在后，代价越来越小。这样希尔排序相比插入排序还是能节省不少时间的。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/5.png"></p>
<p>实现代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public void shellsort (int a[])</span><br><span class="line">&#123;</span><br><span class="line">  int d&#x3D;a.length;</span><br><span class="line">  int team&#x3D;0;&#x2F;&#x2F;临时变量</span><br><span class="line">  for(;d&gt;&#x3D;1;d&#x2F;&#x3D;2)&#x2F;&#x2F;共分成d组</span><br><span class="line">    for(int i&#x3D;d;i&lt;a.length;i++)&#x2F;&#x2F;到那个元素就看这个元素在的那个组即可</span><br><span class="line">    &#123;</span><br><span class="line">      team&#x3D;a[i];</span><br><span class="line">      for(int j&#x3D;i-d;j&gt;&#x3D;0;j-&#x3D;d)</span><br><span class="line">      &#123;    </span><br><span class="line">        if(a[j]&gt;team)</span><br><span class="line">        &#123;</span><br><span class="line">          a[j+d]&#x3D;a[j];</span><br><span class="line">          a[j]&#x3D;team; </span><br><span class="line">        &#125;</span><br><span class="line">        else &#123;</span><br><span class="line">          break;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="选择类排序"><a href="#选择类排序" class="headerlink" title="选择类排序"></a>选择类排序</h2><h3 id="简单选择排序"><a href="#简单选择排序" class="headerlink" title="简单选择排序"></a>简单选择排序</h3><p>简单选择排序（Selection sort）是一种简单直观的排序算法。它的工作原理：首先在未排序序列中找到最小（大）元素，存放到排序序列的起始位置，然后，再从剩余未排序元素中继续寻找最小（大）元素，然后放到<strong>「已排序序列的末尾」</strong>。以此类推，直到所有元素均排序完毕。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/6.png"></p>
<p>实现代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public void selectSort(int[] arr) &#123;</span><br><span class="line">  for (int i &#x3D; 0; i &lt; arr.length - 1; i++) &#123;</span><br><span class="line">    int min &#x3D; i; &#x2F;&#x2F; 最小位置</span><br><span class="line">    for (int j &#x3D; i + 1; j &lt; arr.length; j++) &#123;</span><br><span class="line">      if (arr[j] &lt; arr[min]) &#123;</span><br><span class="line">        min &#x3D; j; &#x2F;&#x2F; 更换最小位置</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    if (min !&#x3D; i) &#123;</span><br><span class="line">      swap(arr, i, min); &#x2F;&#x2F; 与第i个位置进行交换</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">private void swap(int[] arr, int i, int j) &#123;</span><br><span class="line">  int temp &#x3D; arr[i];</span><br><span class="line">  arr[i] &#x3D; arr[j];</span><br><span class="line">  arr[j] &#x3D; temp;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="堆排序"><a href="#堆排序" class="headerlink" title="堆排序"></a>堆排序</h3><p>对于堆排序，首先是建立在堆的基础上，堆是一棵完全二叉树，还要先认识下大根堆和小根堆，完全二叉树中所有节点均大于(或小于)它的孩子节点，所以这里就分为两种情况</p>
<ul>
<li>如果所有节点<strong>「大于」</strong>孩子节点值，那么这个堆叫做<strong>「大根堆」</strong>，堆的最大值在根节点。</li>
<li>如果所有节点<strong>「小于」</strong>孩子节点值，那么这个堆叫做<strong>「小根堆」</strong>，堆的最小值在根节点。</li>
</ul>
<p><img src="/myblogs/2020/11/26/sort-algorithm/7.png"></p>
<p>堆排序首先就是<strong>「建堆」</strong>，然后再是调整。对于二叉树(数组表示)，我们从下往上进行调整，从<strong>「第一个非叶子节点」</strong>开始向前调整，对于调整的规则如下：</p>
<p>建堆是一个O(n)的时间复杂度过程，建堆完成后就需要进行删除头排序。给定数组建堆(creatHeap)</p>
<p>①从第一个非叶子节点开始判断交换下移(shiftDown)，使得当前节点和子孩子能够保持堆的性质</p>
<p>②但是普通节点替换可能没问题，对如果交换打破子孩子堆结构性质，那么就要重新下移(shiftDown)被交换的节点一直到停止。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/8.png"></p>
<p>堆构造完成，取第一个堆顶元素为最小(最大)，剩下左右孩子依然满足堆的性值，但是缺个堆顶元素，如果给孩子调上来，可能会调动太多并且可能破坏堆结构。</p>
<p>①所以索性把最后一个元素放到第一位。这样只需要判断交换下移(shiftDown）,不过需要注意此时整个堆的大小已经发生了变化，我们在逻辑上不会使用被抛弃的位置，所以在设计函数的时候需要附带一个堆大小的参数。</p>
<p>②重复以上操作，一直堆中所有元素都被取得停止。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/9.png"></p>
<p>而堆算法复杂度的分析上，之前建堆时间复杂度是O(n)。而每次删除堆顶然后需要向下交换，每个个数最坏为logn个。这样复杂度就为O(nlogn).总的时间复杂度为O(n)+O(nlogn)=O(nlogn).</p>
<p>实现代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">static void swap(int arr[],int m,int n)</span><br><span class="line">&#123;</span><br><span class="line">  int team&#x3D;arr[m];</span><br><span class="line">  arr[m]&#x3D;arr[n];</span><br><span class="line">  arr[n]&#x3D;team;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;下移交换 把当前节点有效变换成一个堆(小根)</span><br><span class="line">static void shiftDown(int arr[],int index,int len)&#x2F;&#x2F;0 号位置不用</span><br><span class="line">&#123;</span><br><span class="line">  int leftchild&#x3D;index*2+1;&#x2F;&#x2F;左孩子</span><br><span class="line">  int rightchild&#x3D;index*2+2;&#x2F;&#x2F;右孩子</span><br><span class="line">  if(leftchild&gt;&#x3D;len)</span><br><span class="line">    return;</span><br><span class="line">  else if(rightchild&lt;len&amp;&amp;arr[rightchild]&lt;arr[index]&amp;&amp;arr[rightchild]&lt;arr[leftchild])&#x2F;&#x2F;右孩子在范围内并且应该交换</span><br><span class="line">  &#123;</span><br><span class="line">    swap(arr, index, rightchild);&#x2F;&#x2F;交换节点值</span><br><span class="line">    shiftDown(arr, rightchild, len);&#x2F;&#x2F;可能会对孩子节点的堆有影响，向下重构</span><br><span class="line">  &#125;</span><br><span class="line">  else if(arr[leftchild]&lt;arr[index])&#x2F;&#x2F;交换左孩子</span><br><span class="line">  &#123;</span><br><span class="line">    swap(arr, index, leftchild);</span><br><span class="line">    shiftDown(arr, leftchild, len);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;将数组创建成堆</span><br><span class="line">static void creatHeap(int arr[])</span><br><span class="line">&#123;</span><br><span class="line">  for(int i&#x3D;arr.length&#x2F;2;i&gt;&#x3D;0;i--)</span><br><span class="line">  &#123;</span><br><span class="line">    shiftDown(arr, i,arr.length);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">static void heapSort(int arr[])</span><br><span class="line">&#123;</span><br><span class="line">  System.out.println(&quot;原始数组为         ：&quot;+Arrays.toString(arr));</span><br><span class="line">  int val[]&#x3D;new int[arr.length]; &#x2F;&#x2F;临时储存结果</span><br><span class="line">  &#x2F;&#x2F;step1建堆</span><br><span class="line">  creatHeap(arr);</span><br><span class="line">  System.out.println(&quot;建堆后的序列为  ：&quot;+Arrays.toString(arr));</span><br><span class="line">  &#x2F;&#x2F;step2 进行n次取值建堆，每次取堆顶元素放到val数组中，最终结果即为一个递增排序的序列</span><br><span class="line">  for(int i&#x3D;0;i&lt;arr.length;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    val[i]&#x3D;arr[0];&#x2F;&#x2F;将堆顶放入结果中</span><br><span class="line">    arr[0]&#x3D;arr[arr.length-1-i];&#x2F;&#x2F;删除堆顶元素，将末尾元素放到堆顶</span><br><span class="line">    shiftDown(arr, 0, arr.length-i);&#x2F;&#x2F;将这个堆调整为合法的小根堆，注意(逻辑上的)长度有变化</span><br><span class="line">  &#125;</span><br><span class="line">  &#x2F;&#x2F;数值克隆复制</span><br><span class="line">  for(int i&#x3D;0;i&lt;arr.length;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    arr[i]&#x3D;val[i];</span><br><span class="line">  &#125;</span><br><span class="line">  System.out.println(&quot;堆排序后的序列为:&quot;+Arrays.toString(arr));</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="归并类排序"><a href="#归并类排序" class="headerlink" title="归并类排序"></a>归并类排序</h2><p>在归并类排序一般只讲归并排序，但是归并排序也分二路归并、多路归并，这里就讲较多的二路归并排序，且用递归方式实现。</p>
<h3 id="归并排序"><a href="#归并排序" class="headerlink" title="归并排序"></a>归并排序</h3><p>归并和快排都是<strong>「基于分治算法」</strong>的，分治算法其实应用挺多的，很多分治会用到递归，但事实上<strong>「分治和递归是两把事」</strong>。分治就是分而治之，可以采用递归实现，也可以自己遍历实现非递归方式。而归并排序就是先将问题分解成代价较小的子问题，子问题再采取代价较小的合并方式完成一个排序。</p>
<p>至于归并的思想是这样的：</p>
<ul>
<li>第一次：整串先进行划分成一个一个单独，第一次是将序列中(<code>1 2 3 4 5 6---</code>)两两归并成有序，归并完(<code>xx xx xx xx----</code>)这样局部有序的序列。</li>
<li>第二次就是两两归并成若干四个(<code>1 2 3 4 5 6 7 8 ----</code>)<strong>「每个小局部是有序的」</strong>。</li>
<li>就这样一直到最后这个串串只剩一个，然而这个耗费的总次数logn。每次操作的时间复杂的又是<code>O(n)</code>。所以总共的时间复杂度为<code>O(nlogn)</code>.</li>
</ul>
<p><img src="/myblogs/2020/11/26/sort-algorithm/10.png"></p>
<p>合并为一个O(n)的过程：</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/11.png"></p>
<p>实现代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">private static void mergesort(int[] array, int left, int right) &#123;</span><br><span class="line">  int mid&#x3D;(left+right)&#x2F;2;</span><br><span class="line">  if(left&lt;right)</span><br><span class="line">  &#123;</span><br><span class="line">    mergesort(array, left, mid);</span><br><span class="line">    mergesort(array, mid+1, right);</span><br><span class="line">    merge(array, left,mid, right);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">private static void merge(int[] array, int l, int mid, int r) &#123;</span><br><span class="line">  int lindex&#x3D;l;int rindex&#x3D;mid+1;</span><br><span class="line">  int team[]&#x3D;new int[r-l+1];</span><br><span class="line">  int teamindex&#x3D;0;</span><br><span class="line">  while (lindex&lt;&#x3D;mid&amp;&amp;rindex&lt;&#x3D;r) &#123;&#x2F;&#x2F;先左右比较合并</span><br><span class="line">    if(array[lindex]&lt;&#x3D;array[rindex])</span><br><span class="line">    &#123;</span><br><span class="line">      team[teamindex++]&#x3D;array[lindex++];</span><br><span class="line">    &#125;</span><br><span class="line">    else &#123;    </span><br><span class="line">      team[teamindex++]&#x3D;array[rindex++];</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  while(lindex&lt;&#x3D;mid)&#x2F;&#x2F;当一个越界后剩余按序列添加即可</span><br><span class="line">  &#123;</span><br><span class="line">    team[teamindex++]&#x3D;array[lindex++];</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">  while(rindex&lt;&#x3D;r)</span><br><span class="line">  &#123;</span><br><span class="line">    team[teamindex++]&#x3D;array[rindex++];</span><br><span class="line">  &#125; </span><br><span class="line">  for(int i&#x3D;0;i&lt;teamindex;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    array[l+i]&#x3D;team[i];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="桶类排序"><a href="#桶类排序" class="headerlink" title="桶类排序"></a>桶类排序</h2><h3 id="桶排序"><a href="#桶排序" class="headerlink" title="桶排序"></a>桶排序</h3><p>桶排序是一种用空间换取时间的排序，桶排序重要的是它的思想，而不是具体实现，时间复杂度最好可能是线性O(n)，桶排序不是基于比较的排序而是一种分配式的。桶排序从字面的意思上看：</p>
<ul>
<li>桶：若干个桶，说明此类排序将数据放入若干个桶中。</li>
<li>桶：每个桶有容量，桶是有一定容积的容器，所以每个桶中可能有多个元素。</li>
<li>桶：从整体来看，整个排序更希望桶能够更匀称，即既不溢出(太多)又不太少。</li>
</ul>
<p>桶排序的思想为：<strong>「将待排序的序列分到若干个桶中，每个桶内的元素再进行个别排序。」</strong> 当然桶排序选择的方案跟具体的数据有关系，桶排序是一个比较广泛的概念，并且计数排序是一种特殊的桶排序，基数排序也是建立在桶排序的基础上。在数据分布均匀且每个桶元素趋近一个时间复杂度能达到O(n),但是如果数据范围较大且相对集中就不太适合使用桶排序。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/12.jpg"></p>
<p>实现一个简单桶排序：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">import java.util.ArrayList;</span><br><span class="line">import java.util.List;</span><br><span class="line">&#x2F;&#x2F;微信公众号：bigsai</span><br><span class="line">public class bucketSort &#123;</span><br><span class="line"> public static void main(String[] args) &#123;</span><br><span class="line">  int a[]&#x3D; &#123;1,8,7,44,42,46,38,34,33,17,15,16,27,28,24&#125;;</span><br><span class="line">  List[] buckets&#x3D;new ArrayList[5];</span><br><span class="line">  for(int i&#x3D;0;i&lt;buckets.length;i++)&#x2F;&#x2F;初始化</span><br><span class="line">  &#123;</span><br><span class="line">   buckets[i]&#x3D;new ArrayList&lt;Integer&gt;();</span><br><span class="line">  &#125;</span><br><span class="line">  for(int i&#x3D;0;i&lt;a.length;i++)&#x2F;&#x2F;将待排序序列放入对应桶中</span><br><span class="line">  &#123;</span><br><span class="line">   int index&#x3D;a[i]&#x2F;10;&#x2F;&#x2F;对应的桶号</span><br><span class="line">   buckets[index].add(a[i]);</span><br><span class="line">  &#125;</span><br><span class="line">  for(int i&#x3D;0;i&lt;buckets.length;i++)&#x2F;&#x2F;每个桶内进行排序(使用系统自带快排)</span><br><span class="line">  &#123;</span><br><span class="line">   buckets[i].sort(null);</span><br><span class="line">   for(int j&#x3D;0;j&lt;buckets[i].size();j++)&#x2F;&#x2F;顺便打印输出</span><br><span class="line">   &#123;</span><br><span class="line">    System.out.print(buckets[i].get(j)+&quot; &quot;);</span><br><span class="line">   &#125;</span><br><span class="line">  &#125; </span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="计数排序"><a href="#计数排序" class="headerlink" title="计数排序"></a>计数排序</h3><p>计数排序是一种特殊的桶排序，每个桶的大小为1，每个桶不在用List表示，而通常用一个值用来计数。</p>
<p>在<strong>「设计具体算法的时候」</strong>，先找到最小值min，再找最大值max。然后创建这个区间大小的数组,从min的位置开始计数，这样就可以最大程度的压缩空间，提高空间的使用效率。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/13.png"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public static void countSort(int a[])</span><br><span class="line">&#123;</span><br><span class="line">  int min&#x3D;Integer.MAX_VALUE;int max&#x3D;Integer.MIN_VALUE;</span><br><span class="line">  for(int i&#x3D;0;i&lt;a.length;i++)&#x2F;&#x2F;找到max和min</span><br><span class="line">  &#123;</span><br><span class="line">    if(a[i]&lt;min) </span><br><span class="line">      min&#x3D;a[i];</span><br><span class="line">    if(a[i]&gt;max)</span><br><span class="line">      max&#x3D;a[i];</span><br><span class="line">  &#125;</span><br><span class="line">  int count[]&#x3D;new int[max-min+1];&#x2F;&#x2F;对元素进行计数</span><br><span class="line">  for(int i&#x3D;0;i&lt;a.length;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    count[a[i]-min]++;</span><br><span class="line">  &#125;</span><br><span class="line">  &#x2F;&#x2F;排序取值</span><br><span class="line">  int index&#x3D;0;</span><br><span class="line">  for(int i&#x3D;0;i&lt;count.length;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    while (count[i]--&gt;0) &#123;</span><br><span class="line">      a[index++]&#x3D;i+min;&#x2F;&#x2F;有min才是真正值</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="基数排序"><a href="#基数排序" class="headerlink" title="基数排序"></a>基数排序</h3><p>基数排序是一种很容易理解但是比较难实现(优化)的算法。基数排序也称为卡片排序，基数排序的原理就是多次利用计数排序(计数排序是一种特殊的桶排序)，但是和前面的普通桶排序和计数排序有所区别的是，<strong>「基数排序并不是将一个整体分配到一个桶中」</strong>，而是将自身拆分成一个个组成的元素，每个元素分别顺序分配放入桶中、顺序收集，当从前往后或者从后往前每个位置都进行过这样顺序的分配、收集后，就获得了一个有序的数列。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/14.jpg"></p>
<p>如果是数字类型排序，那么这个桶只需要装0-9大小的数字，但是如果是字符类型，那么就需要注意ASCII的范围。</p>
<p>所以遇到这种情况我们基数排序思想很简单，就拿 934，241，3366，4399这几个数字进行基数排序的一趟过程来看，第一次会根据各位进行分配、收集：</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/15.jpg"></p>
<p>分配和收集都是有序的，第二次会根据十位进行分配、收集，此次是在第一次个位分配、收集基础上进行的，所以所有数字单看个位十位是有序的。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/16.jpg"></p>
<p>而第三次就是对百位进行分配收集，此次完成之后百位及其以下是有序的。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/17.jpg"></p>
<p>而最后一次的时候进行处理的时候，千位有的数字需要补零，这次完毕后后千位及以后都有序，即整个序列排序完成。</p>
<p><img src="/myblogs/2020/11/26/sort-algorithm/18.jpg"></p>
<p>简单实现代码为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">static void radixSort(int[] arr)&#x2F;&#x2F;int 类型 从右往左</span><br><span class="line">&#123;</span><br><span class="line">  List&lt;Integer&gt;bucket[]&#x3D;new ArrayList[10];</span><br><span class="line">  for(int i&#x3D;0;i&lt;10;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    bucket[i]&#x3D;new ArrayList&lt;Integer&gt;();</span><br><span class="line">  &#125;</span><br><span class="line">  &#x2F;&#x2F;找到最大值</span><br><span class="line">  int max&#x3D;0;&#x2F;&#x2F;假设都是正数</span><br><span class="line">  for(int i&#x3D;0;i&lt;arr.length;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    if(arr[i]&gt;max)</span><br><span class="line">      max&#x3D;arr[i];</span><br><span class="line">  &#125;</span><br><span class="line">  int divideNum&#x3D;1;&#x2F;&#x2F;1 10 100 100……用来求对应位的数字</span><br><span class="line">  while (max&gt;0) &#123;&#x2F;&#x2F;max 和num 控制</span><br><span class="line">    for(int num:arr)</span><br><span class="line">    &#123;</span><br><span class="line">      bucket[(num&#x2F;divideNum)%10].add(num);&#x2F;&#x2F;分配 将对应位置的数字放到对应bucket中</span><br><span class="line">    &#125;</span><br><span class="line">    divideNum*&#x3D;10;</span><br><span class="line">    max&#x2F;&#x3D;10;</span><br><span class="line">    int idx&#x3D;0;</span><br><span class="line">    &#x2F;&#x2F;收集 重新捡起数据</span><br><span class="line">    for(List&lt;Integer&gt;list:bucket)</span><br><span class="line">    &#123;</span><br><span class="line">      for(int num:list)</span><br><span class="line">      &#123;</span><br><span class="line">        arr[idx++]&#x3D;num;</span><br><span class="line">      &#125;</span><br><span class="line">      list.clear();&#x2F;&#x2F;收集完需要清空留下次继续使用</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当然，基数排序还有字符串等长、不等长、一维数组优化等各种实现需要需学习，具体可以参考公众号内其他文章。</p>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>本次十大排序就这么潇洒的过了一遍，我想大家都应该有所领悟了吧！对于算法总结，避免不必要的劳动力，我分享这个表格给大家：</p>
<table>
<thead>
<tr>
<th align="left">排序算法</th>
<th align="left">平均时间复杂度</th>
<th align="left">最好</th>
<th align="left">最坏</th>
<th align="left">空间复杂度</th>
<th align="left">稳定性</th>
</tr>
</thead>
<tbody><tr>
<td align="left">冒泡排序</td>
<td align="left">O(n^2)</td>
<td align="left">O(n)</td>
<td align="left">O(n^2)</td>
<td align="left">O(1)</td>
<td align="left">稳定</td>
</tr>
<tr>
<td align="left">快速排序</td>
<td align="left">O(nlogn)</td>
<td align="left">O(nlogn)</td>
<td align="left">O(n^2)</td>
<td align="left">O(logn)</td>
<td align="left">不稳定</td>
</tr>
<tr>
<td align="left">插入排序</td>
<td align="left">O(n^2)</td>
<td align="left">O(n)</td>
<td align="left">O(n^2)</td>
<td align="left">O(1)</td>
<td align="left">稳定</td>
</tr>
<tr>
<td align="left">希尔排序</td>
<td align="left">O(n^1.3)</td>
<td align="left">O(n)</td>
<td align="left">O(nlog2n)</td>
<td align="left">O(1)</td>
<td align="left">不稳定</td>
</tr>
<tr>
<td align="left">选择排序</td>
<td align="left">O(n^2)</td>
<td align="left">O(n^2)</td>
<td align="left">O(n^2)</td>
<td align="left">O(1)</td>
<td align="left">不稳定</td>
</tr>
<tr>
<td align="left">堆排序</td>
<td align="left">O(nlogn)</td>
<td align="left">O(nlogn)</td>
<td align="left">O(nlogn)</td>
<td align="left">O(1)</td>
<td align="left">不稳定</td>
</tr>
<tr>
<td align="left">归并排序</td>
<td align="left">O(nlogn)</td>
<td align="left">O(nlogn)</td>
<td align="left">O(nlogn)</td>
<td align="left">O(n)</td>
<td align="left">稳定</td>
</tr>
<tr>
<td align="left">桶排序</td>
<td align="left">O(n+k)</td>
<td align="left">O(n+k)</td>
<td align="left">O(n+k)</td>
<td align="left">O(n+k)</td>
<td align="left">稳定</td>
</tr>
<tr>
<td align="left">计数排序</td>
<td align="left">O(n+k)</td>
<td align="left">O(n+k)</td>
<td align="left">O(n+k)</td>
<td align="left">O(k)</td>
<td align="left">稳定</td>
</tr>
<tr>
<td align="left">基数排序</td>
<td align="left">O(n*k)</td>
<td align="left">O(n*k)</td>
<td align="left">O(n*k)</td>
<td align="left">O(n+k)</td>
<td align="left">稳定</td>
</tr>
</tbody></table>
<h2 id="END"><a href="#END" class="headerlink" title="END"></a>END</h2>
      
    </div>
    
    
    
    
    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Joy Wang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://joy_24.gitee.io/2020/11/26/sort-algorithm/" title="程序员必知必会的十大算法">https://joy_24.gitee.io/2020/11/26/sort-algorithm/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/myblogs/tags/%E6%8E%92%E5%BA%8F-%E7%AE%97%E6%B3%95/" rel="tag"># 排序,算法</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/myblogs/2020/11/26/idea-hotKey-1/" rel="next" title="idea 这样配置，快到飞起">
                <i class="fa fa-chevron-left"></i> idea 这样配置，快到飞起
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/myblogs/2020/11/27/gradleConfig/" rel="prev" title="idea里gradle配置和使用">
                idea里gradle配置和使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/myblogs/uploads/avatar.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                #<a href="/myblogs/archives%7C%7C%20archive">
                <a href="/myblogs/archives">
              
                  <span class="site-state-item-count">34</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/myblogs/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/myblogs/tags/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/myblogs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/joyWJ" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="wangjianjoy@126.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BB%AA%E8%AE%BA"><span class="nav-number">1.</span> <span class="nav-text">绪论</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%A4%E6%8D%A2%E7%B1%BB"><span class="nav-number">2.</span> <span class="nav-text">交换类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F"><span class="nav-number">2.1.</span> <span class="nav-text">冒泡排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F"><span class="nav-number">2.2.</span> <span class="nav-text">快速排序</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8F%92%E5%85%A5%E7%B1%BB%E6%8E%92%E5%BA%8F"><span class="nav-number">3.</span> <span class="nav-text">插入类排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%9B%B4%E6%8E%A5%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F"><span class="nav-number">3.1.</span> <span class="nav-text">直接插入排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B8%8C%E5%B0%94%E6%8E%92%E5%BA%8F"><span class="nav-number">3.2.</span> <span class="nav-text">希尔排序</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%80%89%E6%8B%A9%E7%B1%BB%E6%8E%92%E5%BA%8F"><span class="nav-number">4.</span> <span class="nav-text">选择类排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F"><span class="nav-number">4.1.</span> <span class="nav-text">简单选择排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A0%86%E6%8E%92%E5%BA%8F"><span class="nav-number">4.2.</span> <span class="nav-text">堆排序</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BD%92%E5%B9%B6%E7%B1%BB%E6%8E%92%E5%BA%8F"><span class="nav-number">5.</span> <span class="nav-text">归并类排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F"><span class="nav-number">5.1.</span> <span class="nav-text">归并排序</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A1%B6%E7%B1%BB%E6%8E%92%E5%BA%8F"><span class="nav-number">6.</span> <span class="nav-text">桶类排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A1%B6%E6%8E%92%E5%BA%8F"><span class="nav-number">6.1.</span> <span class="nav-text">桶排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AE%A1%E6%95%B0%E6%8E%92%E5%BA%8F"><span class="nav-number">6.2.</span> <span class="nav-text">计数排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9F%BA%E6%95%B0%E6%8E%92%E5%BA%8F"><span class="nav-number">6.3.</span> <span class="nav-text">基数排序</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BB%93%E8%AF%AD"><span class="nav-number">7.</span> <span class="nav-text">结语</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#END"><span class="nav-number">8.</span> <span class="nav-text">END</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Joy Wang</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/myblogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/myblogs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblogs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/myblogs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/myblogs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/myblogs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/myblogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
